package com.zhoutao.blog.seven.dao.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhoutao.blog.seven.dao.mapper.BlogCategoryMapper;
import com.zhoutao.blog.seven.dao.model.BlogCategoryDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Repository
public class BlogCategoryRepository extends ServiceImpl<BlogCategoryMapper, BlogCategoryDao> {
    public Optional<BlogCategoryDao> findByName(String category) {
        if (!StringUtils.hasText(category)) {
            return Optional.empty();
        }
        LambdaQueryWrapper<BlogCategoryDao> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BlogCategoryDao::getTitle, category);
        wrapper.orderByDesc(BlogCategoryDao::getId);
        return Optional.ofNullable(this.getOne(wrapper));
    }

    /**
     * 查询全部的数据，根据分组ID 进行 map 变换
     *
     * @return
     */
    public Map<Long, BlogCategoryDao> mapGroupById() {
        List<BlogCategoryDao> categoryDaos = this.list();
        if (CollectionUtils.isEmpty(categoryDaos)) {
            return Collections.emptyMap();
        }

        return categoryDaos.stream().collect(Collectors.toMap(BlogCategoryDao::getId, Function.identity()));
    }
}
